package com.cuitrip.push;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.cuitrip.app.MainApplication;
import com.cuitrip.business.order.detail.OrderFormActivity;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.reminder.RemindDialogActivity;
import com.cuitrip.push.model.PushMessageModel;
import com.cuitrip.push.model.TypeKeyMap;
import com.cuitrip.service.R;
import com.cuitrip.util.PackageUtil;
import com.lab.utils.LogHelper;
import com.umeng.message.UTrack;
import com.umeng.message.UmengBaseIntentService;
import com.umeng.message.entity.UMessage;

import org.android.agoo.client.BaseConstants;
import org.json.JSONObject;

import java.util.Map;
import java.util.Random;

/**
 * Created on 7/19.
 */
public class PushService extends UmengBaseIntentService {
    private static final String TAG = "PushService";
    private static int MESSAGE_ID = 12345;

    public static String PUSH_KEY = "push_key";
    public static String USER_TYPE_KEY = "user_type_key";

// 如果需要打开Activity，请调用Intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)；否则无法打开Activity。

    public static final String NEW_MESSAGE_BROADCAT = "ct_new_message_coming";
    public static final String NEW_MESSAGE_TYPE = "ct_new_message_type";
    public static final String MESSAGE_BODY = "message_body";

    private static final String UMENG_MESSAGE_ID = "messageId";

    private static final String UMENG_MESSAGE_ACTION = "goto";

    private static final String UMENG_MESSAGE_ACTION_ORDER_DETAIL = "orderDetail";
    private static final String UMENG_MESSAGE_ACTION_CHAT_DETAIL = "chatDetail";

    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.e(TAG, "onMessage: " + intent.toString());
        super.onMessage(context, intent);
        try {
            String message = intent.getStringExtra(BaseConstants.MESSAGE_BODY);
            Log.e(TAG, "onMessage: " + message);
            JSONObject jsonObject = new JSONObject(message);

            JSONObject extra = jsonObject.getJSONObject("extra");
            int userType = -1;
            if (extra != null) {
                PushMessageModel pushMessageModel = JSON.parseObject(extra.toString(), PushMessageModel.class);

                boolean orderNotification = showReminder(context, pushMessageModel);
                if (orderNotification) {
                    userType = pushMessageModel.getUserType();
                }
            }
            UMessage msg = new UMessage(jsonObject);
            UTrack.getInstance(context).trackMsgDisplay(msg);
            updateMsg(context, msg, message, userType);
            Log.e(TAG, "onMessage: end");
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void updateMsg(Context context, UMessage msg, String messageBody, int userType) {
        if (msg.extra != null && !TextUtils.isEmpty(msg.extra.get("gmtCreated"))) {
            MessagePrefs.saveLastMessageTime(msg.extra.get("gmtCreated"));
        }
        MessagePrefs.setHasNewMessage(true);
        showNotification(context, msg, messageBody, userType);
        context.sendBroadcast(new Intent(NEW_MESSAGE_BROADCAT));
    }

    private void showNotification(Context context, UMessage msg, String messageBody, int userType) {
        Intent resultIntent = new Intent("android.intent.action.VIEW");
        resultIntent.addCategory("android.intent.category.BROWSABLE");
        String schemeUrl = msg.extra.get("goto");
        if (!TextUtils.isEmpty(schemeUrl)) {
            resultIntent.setData(Uri.parse(schemeUrl));
        }
        resultIntent.putExtra(PUSH_KEY, true);
        resultIntent.putExtra(MESSAGE_BODY, messageBody);
        if (userType != -1) {
            resultIntent.putExtra(USER_TYPE_KEY, userType);
        }
        PendingIntent pendingIntent = getPending(msg);
        if (pendingIntent == null) {
            pendingIntent = PendingIntent.getActivity(context, new Random().nextInt() % 10000, resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        }

        Notification notification = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ct_icon)
                .setTicker(msg.title).setContentTitle(msg.title).setContentText(msg.text)
                .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                .setContentIntent(pendingIntent)
                .build();
        NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
        managerCompat.notify(new Random().nextInt() % 10000, notification);
    }

    public PendingIntent getPending(UMessage message) {
        LogHelper.e(TAG, "getPending");
        PendingIntent result = null;
        try {
            Map<String, String> valus = message.extra;
            if (valus == null) {

                LogHelper.e(TAG, "no valus");
            }
            if (valus != null && valus.containsKey(UMENG_MESSAGE_ACTION)) {

                LogHelper.e(TAG, "has value");
                switch (valus.get(UMENG_MESSAGE_ACTION)) {
                    case UMENG_MESSAGE_ACTION_ORDER_DETAIL:
                        if (!valus.containsKey(UMENG_MESSAGE_ID)) {
                            LogHelper.e(TAG, "no messageId");
                            break;
                        }
                    {
                        String oid = valus.get(UMENG_MESSAGE_ID);
                        LogHelper.e(TAG, "has value " + UMENG_MESSAGE_ACTION_ORDER_DETAIL + "|" + oid);
                        Intent notificationIntent = OrderFormActivity.getStartOrderIntent(MainApplication.getInstance(), oid);
                        notificationIntent.setFlags(notificationIntent.FLAG_ACTIVITY_NEW_TASK);
                        result = PendingIntent.getActivity(MainApplication.getInstance(), oid.hashCode(),
                                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    }
                    break;
                    case UMENG_MESSAGE_ACTION_CHAT_DETAIL:
                        if (!valus.containsKey(UMENG_MESSAGE_ID)) {
                            LogHelper.e(TAG, "no messageId");
                            break;
                        }
                    {
                        String oid = valus.get(UMENG_MESSAGE_ID);
                        LogHelper.e(TAG, "has value " + UMENG_MESSAGE_ACTION_CHAT_DETAIL + "|" + oid);
                        Intent notificationIntent = OrderFormActivity.getStartConversationIntent(MainApplication.getInstance(), oid);
                        notificationIntent.setFlags(notificationIntent.FLAG_ACTIVITY_NEW_TASK);
                        result = PendingIntent.getActivity(MainApplication.getInstance(), oid.hashCode(),
                                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    }
                    break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {

            LogHelper.e(TAG, " JSON error " + e.getMessage());
        }
        return result;
    }

    private boolean showReminder(Context context, PushMessageModel model) {
        if (model == null || !TypeKeyMap.isPushModelNeedRemind(model.getMessageType())) {
            return false;
        }
        Intent intent = new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION);
        intent.putExtra(OrderItem.KEY_ORDER_ID, model.getMessageId());
        context.sendBroadcast(intent);

        if (PackageUtil.isOurApp(context)) {
            Intent activityIntent = new Intent(context, RemindDialogActivity.class);
            activityIntent.putExtra(RemindDialogActivity.DATA_KEY, model);
            activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(activityIntent);
        }
        return true;
    }


}
